﻿#include "spectrumplaybackwebsocketclient.h"
#include "spectrumplaybackwebsocketserver.h"

#include <QUuid>
#include <qglobalconfig.h>

QMutex SpectrumPlaybackWebSocketServer::mutex;
SpectrumPlaybackWebSocketServer* SpectrumPlaybackWebSocketServer::instance = nullptr;

SpectrumPlaybackWebSocketServer *SpectrumPlaybackWebSocketServer::getInstance()
{
    if (instance == nullptr) {
        QMutexLocker locker(&mutex);
        if (instance == nullptr) {
            instance = new SpectrumPlaybackWebSocketServer();
        }
    }
    return instance;
}

void SpectrumPlaybackWebSocketServer::deleteInstance()
{
    if (instance != nullptr) {
        delete instance;
        instance = nullptr;
    }
}


SpectrumPlaybackWebSocketServer::SpectrumPlaybackWebSocketServer(QObject *parent) : QThread(parent)
{
    moveToThread(this); // 确保对象在自己的线程中运行
    qRegisterMetaType<QWebSocket*>("QWebSocket*");
    start();
}

SpectrumPlaybackWebSocketServer::~SpectrumPlaybackWebSocketServer()
{
    quit();
    wait();
}

void SpectrumPlaybackWebSocketServer::handleNewConnection()
{
    QWebSocket *pSocket = m_server->nextPendingConnection();
//    QThread *thread = new QThread;
    SpectrumPlaybackWebSocketClient *pClient = new SpectrumPlaybackWebSocketClient(pSocket);
//    pClient->moveToThread(thread);
    // 清理资源
//    connect(pClient, &SpectrumPlaybackWebSocketClient::destroyed, thread, &QThread::quit);
//    connect(thread, &QThread::finished, thread, &QObject::deleteLater);
//    thread->start();
}

void SpectrumPlaybackWebSocketServer::run()
{
    QString adderss = QGlobalConfig::getInstance().read("SpectrumPlayback","websocket_adderss","127.0.0.1").toString();
    quint16 prot = QGlobalConfig::getInstance().read("SpectrumPlayback","websocket_port",22203).toUInt();
    m_server = new QWebSocketServer(QStringLiteral("SpectrumPlayback WebSocket Server"), QWebSocketServer::NonSecureMode, this);

    if (m_server->listen(QHostAddress(adderss), prot)) {
        qDebug() << __FUNCTION__ << "WebSocket server listening on port" << prot << "in thread" << QThread::currentThreadId();
        connect(m_server, &QWebSocketServer::newConnection, this, &SpectrumPlaybackWebSocketServer::handleNewConnection);
    } else {
        qCritical() << "Failed to start WebSocket server";
    }
    exec(); // 进入事件循环，等待处理新连接
}
